package com.haierp.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haierp.enums.ItemStatus;
import com.haierp.model.ErpOrder;
import com.haierp.model.Inventory;
import com.haierp.model.Item;
import com.haierp.model.ItemSku;
import com.haierp.model.ScaleType;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemService;
import com.haierp.service.IItemSkuService;
import com.haierp.service.IScaleTypeService;
import com.haierp.service.item.IOuterItemService;
import com.haierp.util.ImageUtil;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.util.ExcelTool.ExcelHelper;
import com.haierp.vo.ItemQueryVO;
import com.haierp.vo.ItemSkuQueryVO;
import com.haierp.vo.json.PicModel;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.HaiJsonUtils;
/**
 * 商品SKU处理器
 * @author zhulu
 *
 */
@Controller
@RequestMapping("/itemSku")
public class ItemSkuController extends BaseController {

	@Autowired
	private IItemSkuService iItemSkuService;
	@Autowired
	private IItemService iItemService;
	@Autowired
	private IScaleTypeService iScaleTypeService;
	@Autowired
	private IInventoryService inventoryService;
	@Autowired
	private IErpOrderService erpOrderService;
	@Autowired
	private IOuterItemService outerItemService;

	
	
	/**
	 * 添加商品
	 *
	 * @param
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Object update(ItemSku itemSku) {
		JsonResult<ItemSku> result = new JsonResult<>();
		ShiroUser shiroUser = this.getShiroUser();
		//if haven't item id ,add item
		if(itemSku.getId()==null){
			
			return result.buildIsSuccess(false).buildMsg("没有SKU id");
		}else{
			//当upc改变时，订正订单明细里面的upc数据
			ItemSku selItemSku = iItemSkuService.selectById(itemSku.getId());
			if(StringUtil.isNotBlank(itemSku.getUpc())) {
				ErpOrder erpOrder = new ErpOrder();
				erpOrder.setSkuId(itemSku.getId());
				erpOrder.setUpc(itemSku.getUpc());
				erpOrderService.updateUpcForOrder(erpOrder);
			}
			//当weight改变时，订正订单明细里面的weight数据
			if(itemSku.getWeight()!=null && itemSku.getWeight()!=selItemSku.getWeight()) {
				ErpOrder erpOrder = new ErpOrder();
				erpOrder.setSkuId(itemSku.getId());
				erpOrder.setWeight(itemSku.getWeight());
				erpOrderService.updateWeightForOrder(erpOrder);
			}
			
			//1. find item
			Item item = iItemService.selectById(itemSku.getItemId());
			if(item==null){
				return result.buildMsg("the item is not find").buildIsSuccess(false);
			}
			itemSku.setItemCode(item.getItemCode());
			itemSku.setCategoryId(item.getCategoryId());
			itemSku.setCategoryName(item.getCategoryName());
			itemSku.setItemId(item.getId());
			itemSku.setItemName(item.getName());
			String skuPic = ImageUtil.getImageUrl(itemSku.getSkuPic());
			itemSku.setSkuPic(skuPic);
			//2.init 
			itemSku.setUserModify(shiroUser.getName());
			itemSku.setGmtModify(new Date());
//			iItemSkuService.updateById(itemSku);
			iItemSkuService.updateItemSku(itemSku);
			
			//同步到有赞
			try {
				if(item.getIsSale()!=null && item.getIsSale()==1 && item.getCompanyId()==1) {
					if(item.getStatus()==ItemStatus.DELISTING.getCode()) {
						outerItemService.listingYouzan(item);
					}
					outerItemService.synItemYouzan(item.getId());
				} else {
					outerItemService.delistingYouzan(item);
				}
			} catch(Exception e) {
				logger.error("SKU修改时同步到有赞：", e);
			}
			
			return result.buildIsSuccess(true);
		}
		
		
	}
	
	
	@RequestMapping("/query")
	@ResponseBody
	public Object query(Long id) {
		JsonResult<ItemSku> result = new JsonResult<>();
		//if haven't item id ,add item
		if(id!=null){
			ItemQueryVO itemQueryVO = new ItemQueryVO();
			itemQueryVO.setSkuId(id);
			result.setData(iItemSkuService.queryItemSkusBySkuId(itemQueryVO));
		}else{
			result.buildIsSuccess(false).buildMsg("没有SKU id");
		}
		return result.buildIsSuccess(true);
	}
	
	@RequestMapping("/queryBySkuCodeOrUpc")
	@ResponseBody
	public Object queryBySkuCodeOrUpc(String code) {
		JsonPageResult<List<ItemSku>> result = new JsonPageResult<>();
		if(StringUtils.isNoneBlank(code)) {
			List<ItemSku> itemSkuList = null;
			ItemSku tjItemSku = new ItemSku();
			tjItemSku.setSkuCode(code);
			tjItemSku.setSkuStatus(0);
			ItemSku selItemSku = iItemSkuService.selectOne(tjItemSku);
			if(selItemSku != null) {
				itemSkuList = new ArrayList<ItemSku>();
				itemSkuList.add(selItemSku);
			} else {
				tjItemSku.setSkuCode(null);
				tjItemSku.setUpc(code);
				
				EntityWrapper<ItemSku> entityWrapper = new EntityWrapper<ItemSku>();
				entityWrapper.setEntity(tjItemSku);
				itemSkuList = iItemSkuService.selectList(entityWrapper);
			}
			result.setData(itemSkuList);
		} else {
			result.buildIsSuccess(false).buildMsg("skuCode 不能为空");
		}
		return result.buildIsSuccess(true);
	}
	
	@RequestMapping("/queryItemSkuList")
	@ResponseBody
	public Object queryItemSkus(ItemSkuQueryVO itemSkuQueryVO, String skuType) {
		JsonPageResult<List<ItemSku>> result = new JsonPageResult<>();
		try{
			result = iItemSkuService.queryItemSkus(itemSkuQueryVO);
			if(StringUtil.isNotBlank(itemSkuQueryVO.getSkuCode()) && !"1".equals(skuType)) {
				List<ItemSku> ItemSkuList = result.getData();
				Item item = iItemService.selectById(ItemSkuList.get(0).getItemId());
				if(item.getStatus() == 2) {
					result.buildIsSuccess(true).buildMsg("该商品已经下架，慎重建单！");
				}
			}
			result.buildIsSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			result.buildIsSuccess(false);
		}
		return result;
	}
	
	
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(Long id) {
		JsonResult<String> result = new JsonResult<>();
		if(id!=null){
			if(iItemSkuService.isCanDeleteSku(id)) {
				iItemSkuService.deleteSkuById(id);
				return result.buildIsSuccess(true);
			} else {
				return result.buildIsSuccess(false).buildMsg("此sku已有业务记录，不能删除");
			}
		}else{
			return result.buildIsSuccess(false).buildMsg("没有SKU id");
		}
	}
	
	@RequestMapping("/scaleTypeList")
	@ResponseBody
	public Object scaleTypeList() {
		JsonResult<List<ScaleType>> result = new JsonResult<>();
		List<ScaleType> scaleTypeList= iScaleTypeService.getScaleTypeList();
		
		return result.buildData(scaleTypeList).buildIsSuccess(true);
	}
	
	/**
	 * SKU 锁定虚拟库存，用在提前修改可售库存，以便同步到第三方平台(有赞)
	 *
	 * @param
	 * @return
	 */
	@RequestMapping("/lockedVirtualInv")
	@ResponseBody
	public Object lockedVirtualInv(ItemSku itemSku) {
		JsonResult<ItemSku> result = new JsonResult<>();
		if(itemSku.getId()==null) {
			return result.buildIsSuccess(false).buildMsg("SKU ID错误");
		} else if(itemSku.getItemId()==null) {
			return result.buildIsSuccess(false).buildMsg("商品ID错误");
		}
		
		Inventory inventory = inventoryService.queryInventoryBySkuId(itemSku.getItemId(), itemSku.getId());
		if(inventory == null) {
			return result.buildIsSuccess(false).buildMsg("未找到此sku的库存");
		}
		int lockedNum = inventory.getLockedVirtualInv() + itemSku.getLockedVirtualInv();
		if(lockedNum<0 || (lockedNum>inventory.getVirtualInv() && lockedNum>inventory.getTotalAvailableInv())) {
			return result.buildIsSuccess(false).buildMsg("锁定数量异常");
		}
		inventory.setLockedVirtualInv(lockedNum);
		inventoryService.updateSelectiveById(inventory);
		
		//同步到有赞
		Item item = iItemService.selectById(itemSku.getItemId());
		try {
			if(item.getIsSale()!=null && item.getIsSale()==1 && item.getCompanyId()==1) {
				if(item.getStatus()==ItemStatus.DELISTING.getCode()) {
					outerItemService.listingYouzan(item);
				}
				outerItemService.synItemYouzan(item.getId());
			} else {
				outerItemService.delistingYouzan(item);
			}
		} catch(Exception e) {
			logger.error("SKU锁定虚拟库存时同步到有赞：", e);
		}
		return result.buildIsSuccess(true);
	}
	
	/**
	 * 导出excel
	 * @param id
	 */
	@RequestMapping("/queryItemSkusForExcel")
    public ResponseEntity<byte[]> queryItemSkusForExcel() throws Exception {
    	List<List<Object>> rowDatas = new ArrayList<>();
    	List<ItemSku> itemSkuList = iItemSkuService.queryItemSkusForExcel();
    	if(itemSkuList != null) {
    		for (ItemSku itemSku : itemSkuList) {
    			List<Object> list = new ArrayList<>();
    			//sku图片
    			String skuPic = itemSku.getSkuPic();
    			if(StringUtil.isNotBlank(skuPic)) {
    				PicModel pm = HaiJsonUtils.toBean(skuPic, PicModel.class);
        			String imgSrc = pm.getPicList().get(0).getUrl();
        			String imgType = imgSrc.substring(imgSrc.lastIndexOf(".") + 1).toUpperCase();
        			if(imgSrc.contains("aliyuncs.com")) {
        				imgSrc += "?x-oss-process=image/resize,m_lfit,h_100,w_100";
        			} else {
        				imgSrc = imgSrc.replaceAll("Resource", "Thumbnail");
        			}
        			//System.out.println(imgSrc);
        			URL url = new URL(imgSrc);
        			BufferedImage image = ImageIO.read(url);
        			ByteArrayOutputStream output = new ByteArrayOutputStream();
        	        ImageIO.write(image, imgType, output);
        	        output.flush();
        	        list.add(output.toByteArray());
        	        output.close();
    			} else {
    				list.add(null);
    			}
    	        list.add(itemSku.getItemName());	//商品名称
    	        list.add(itemSku.getBrand());       //商品品牌
    	        list.add(itemSku.getColor());		//颜色
    	        list.add(itemSku.getScale());		//尺码
    	        list.add(itemSku.getSalePrice());	//销售价格
    			rowDatas.add(list);
    		}
    	}
    	ExcelHelper excelHelper = new ExcelHelper();
    	String[] columnTitles = new String[]{"商品图片", "商品名称", "商品品牌", "颜色", "尺码", "销售价格"};
    	Integer[] columnWidth = new Integer[]{10, 30, 10, 10, 20, 20};
    	excelHelper.setItemToSheet("Item", columnTitles, rowDatas, columnWidth);
    	//excelHelper.writeToFile("/Users/liuyang/Work/test.xls");
    	
    	ResponseEntity<byte[]> filebyte = null;
    	ByteArrayOutputStream  out = excelHelper.writeToByteArrayOutputStream();
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	String fileName = "商品.xlsx";
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        
        filebyte = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        out.close();
        excelHelper.close();
        return filebyte;
    }
    /**
	 * 修改sku采购站点
	 */
	@RequestMapping("/updateAllSkuBuySite")
	@ResponseBody
	public Object updateAllSkuBuySite(ItemSkuQueryVO itemSkuQueryVO){
		JsonResult<String> result = new JsonResult<>();
		if(StringUtils.isNotEmpty(itemSkuQueryVO.getOldBuySite())) {
			if("".equals(itemSkuQueryVO.getBuySite())) {
				itemSkuQueryVO.setBuySite(null);
			}
			iItemSkuService.updateAllOldBuySite(itemSkuQueryVO);
			iItemService.updateAllOldBuySiteByitem(itemSkuQueryVO);
		}
		return result.buildIsSuccess(true);
	}
}
